/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rmatos.programming.blog.facade;

import com.rmatos.programming.blog.entities.Comments;
import com.rmatos.programming.blog.entities.Tags;
import com.rmatos.programming.blog.entities.Users;
import java.util.ArrayList;
import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author User
 */
@Stateless
public class CommentSessionBean implements CommentSessionBeanLocal {

    @PersistenceContext(unitName = "RMatosBLOG-ejbPU")
    private EntityManager em;

    public void createNewComment(String username, String category, String commentTitle, String commentBody, ArrayList<Tags> tags) {


        Users _user = (Users) em.createNamedQuery("Users.getUserFromName").setParameter("username", username).getSingleResult();
        Comments _currentComment = new Comments();

        _currentComment.setCategory(category);
        _currentComment.setCreationDate(new Date());

        // TODO: change this
        _currentComment.setShortDescription(commentBody.substring(0, 20));

        _currentComment.setTitle(commentTitle);
        _currentComment.setBody(commentBody);
        _currentComment.setOwner(_user);
        _currentComment.setTags(tags);

        setTagsToComment(_currentComment, tags);

        em.persist(_currentComment);


    }

    private void setTagsToComment(Comments comments, ArrayList<Tags> tags) {

        for (int i = 0; i < tags.size(); i++) {

            tags.get(i).setComment(comments);

        }

    }
}
